package com.example.handlercontext;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author by linenxi
 * @Classname HandlerContext
 * @Description
 * @Date 2019/5/5
 */
@Component
public class OrderHandlerContext {

    private Map<String, BasicOrderHandler> annotationHandlerContext = new HashMap<>();

    private Map<String, BasicOrderHandler> classNameHandlerContext = new HashMap<>();

    public OrderHandlerContext(Map<String, BasicOrderHandler> annotationHandlerContext) {
        annotationHandlerContext.values().forEach(basicHandler -> this.annotationHandlerContext.put(basicHandler.getClass().getAnnotation(OrderHandlerType.class).value(), basicHandler));
        annotationHandlerContext.entrySet().forEach(entry -> classNameHandlerContext.put(StringUtils.substringBefore(entry.getKey(), "OrderHandler"), entry.getValue()));
    }

    public BasicOrderHandler getInstance(String type) {
        BasicOrderHandler basicOrderHandler = annotationHandlerContext.get(type);
        if (basicOrderHandler == null) {
            throw new RuntimeException("未找到该容器");
        }
        return basicOrderHandler;
    }

    public BasicOrderHandler getInstance(EnumOrderHandler enumOrderHandler) {
        return getInstance(enumOrderHandler.getType());
    }


}
